package com.xxl.job.admin.controller;

import com.xxl.job.admin.core.model.ConfigItem;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobRegistry;
import com.xxl.job.admin.core.route.ExecutorRouteStrategyEnum;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.dao.XxlJobRegistryDao;
import com.xxl.job.core.commons.base.PageData;
import com.xxl.job.core.commons.exception.DataxException;
import com.xxl.job.core.commons.response.ReturnCode;
import com.xxl.job.core.commons.response.ReturnT;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.enums.RegistryConfig;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * job group controller
 *
 * @author xuxueli 2016-10-02 20:52:56
 */
@RestController
@RequestMapping("/jobgroup")
public class JobGroupController {
    private static Logger logger = LoggerFactory.getLogger(JobGroupController.class);

    @Resource
    public XxlJobInfoDao xxlJobInfoDao;
    @Resource
    public XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobRegistryDao xxlJobRegistryDao;

    @GetMapping("/pageList")
    @ResponseBody
    public ReturnT pageList(HttpServletRequest request,
                            @RequestParam(required = false, defaultValue = "0") int page,
                            @RequestParam(required = false, defaultValue = "10") int limit,
                            String appname, String title) {
        if (page < 1) {
            page = 1;
        }
        // page query
        List<XxlJobGroup> list = xxlJobGroupDao.pageList((page - 1) * limit, limit, appname, title);
        int list_count = xxlJobGroupDao.pageListCount((page - 1) * limit, limit, appname, title);

        // package result
        PageData<XxlJobGroup> pageData = new PageData<>();
        pageData.setList(list);
        pageData.setTotal(list_count);
        return ReturnT.ok().put(pageData);
    }

    @PostMapping("/save")
    @ResponseBody
    public ReturnT save(@RequestBody XxlJobGroup xxlJobGroup) {

        if (null == xxlJobGroup) {
            return ReturnT.error(ReturnCode.INVALID_PARAMETER, "输入执行器参数错误");
        }
        // valid
        checkAppName(xxlJobGroup.getAppname());
        checkTitle(xxlJobGroup.getTitle());
        if (xxlJobGroup.getAddressType() != 0) {
            checkAddressList(xxlJobGroup.getAddressList());
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());

        int ret = xxlJobGroupDao.save(xxlJobGroup);
        return (ret > 0) ? ReturnT.ok() : ReturnT.error();
    }

    @PostMapping("/update")
    @ResponseBody
    public ReturnT update(@RequestBody XxlJobGroup xxlJobGroup) {
        // valid
        XxlJobGroup oldEntity = xxlJobGroupDao.load(xxlJobGroup.getId());
        if (null == oldEntity) {
            return ReturnT.error(ReturnCode.INVALID_PARAMETER.getCode(), "执行器不存在");
        }
        if (!oldEntity.getTitle().equals(xxlJobGroup.getTitle())) {
            checkTitle(xxlJobGroup.getTitle());
        }
        if (!oldEntity.getAppname().equals(xxlJobGroup.getAppname())) {
            checkAppName(xxlJobGroup.getAppname());
        }

        if (xxlJobGroup.getAddressType() == 0) {
            // 0=自动注册
            List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppname());
            String addressListStr = null;
            if (registryList != null && !registryList.isEmpty()) {
                Collections.sort(registryList);
                addressListStr = "";
                for (String item : registryList) {
                    addressListStr += item + ",";
                }
                addressListStr = addressListStr.substring(0, addressListStr.length() - 1);
            }
            xxlJobGroup.setAddressList(addressListStr);
        } else {
            // 1=手动录入
            checkAddressList(xxlJobGroup.getAddressList());
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());
        int ret = xxlJobGroupDao.update(xxlJobGroup);

        return (ret > 0) ? ReturnT.ok() : ReturnT.error();
    }

    private List<String> findRegistryByAppName(String appnameParam) {
        HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>();
        List<XxlJobRegistry> list = xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT, new Date());
        if (list != null) {
            for (XxlJobRegistry item : list) {
                if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
                    String appname = item.getRegistryKey();
                    List<String> registryList = appAddressMap.get(appname);
                    if (registryList == null) {
                        registryList = new ArrayList<String>();
                    }

                    if (!registryList.contains(item.getRegistryValue())) {
                        registryList.add(item.getRegistryValue());
                    }
                    appAddressMap.put(appname, registryList);
                }
            }
        }
        return appAddressMap.get(appnameParam);
    }

    @PostMapping("/remove")
    @ResponseBody
    public ReturnT<String> remove(int id) {

        // valid
        int count = xxlJobInfoDao.pageListCount(0, 10, id, -1, null, null, null);
        if (count > 0) {
            return ReturnT.error(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_del_limit_0"));
        }

        List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
        if (allList.size() == 1) {
            return ReturnT.error(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_del_limit_1"));
        }

        int ret = xxlJobGroupDao.remove(id);
        return (ret > 0) ? ReturnT.ok() : ReturnT.error();
    }

    @RequestMapping("/loadById")
    @ResponseBody
    public ReturnT loadById(int id) {
        XxlJobGroup jobGroup = xxlJobGroupDao.load(id);
       return jobGroup != null ? ReturnT.ok().put(jobGroup) : ReturnT.error(ReturnCode.ERROR,"查询执行器失败");
    }


    @GetMapping("/getRouteStrategyList")
    @ApiOperation(value = "查询路由策略列表")
    public ReturnT getRouteStrategyList() {
        List<ConfigItem> list = new ArrayList<>();
        for (ExecutorRouteStrategyEnum item : ExecutorRouteStrategyEnum.values()) {
            list.add(new ConfigItem(item.getTitle(), item.name(), item.name()));
        }
        return ReturnT.ok().put(list);
    }

    @GetMapping("/getBlockStrategyList")
    @ApiOperation(value = "查询阻塞策略列表")
    public ReturnT getBlockStrategyList() {
        List<ConfigItem> list = new ArrayList<>();
        for (ExecutorBlockStrategyEnum item : ExecutorBlockStrategyEnum.values()) {
            list.add(new ConfigItem(item.getTitle(), item.name(), item.name()));
        }
        return ReturnT.ok().put(list);
    }

    public static void main(String args[]) {
        logger.info("" + ExecutorRouteStrategyEnum.FIRST);
        logger.info("" + ExecutorRouteStrategyEnum.FIRST.name());
    }

    /**
     * 校验title
     */
    private void checkTitle(String title) {
        if (title == null || title.trim().length() == 0) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (title.length() < 4 || title.length() > 50) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title_length")));
        }
        if (xxlJobGroupDao.findByTitle(title).size() > 0) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_title_existed"));
        }
        if (title.contains(">") || title.contains("<")) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
        }
    }

    /**
     * 校验appname
     */
    private void checkAppName(String appname) {
        if (appname == null || appname.trim().length() == 0) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (appname.length() < 4 || appname.length() > 64) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (appname.contains(">") || appname.contains("<")) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), "AppName" + I18nUtil.getString("system_unvalid"));
        }
        if (xxlJobGroupDao.findByAppName(appname).size() > 0) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_appname_existed"));
        }
    }


    /**
     * 校验title
     */
    private void checkAddressList(String addressList) {
        if (addressList == null || addressList.trim().length() == 0) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_addressType_limit"));
        }
        if (addressList.contains(">") || addressList.contains("<")) {
            throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_registryList") + I18nUtil.getString("system_unvalid"));
        }

        String[] addresss = addressList.split(",");
        for (String item : addresss) {
            if (item == null || item.trim().length() == 0) {
                throw new DataxException(ReturnCode.INVALID_PARAMETER.getCode(), I18nUtil.getString("jobgroup_field_registryList_unvalid"));
            }
        }
    }
}
